<?php

namespace App\Admin\Actions\Grid\Row\SwtBjMachine;

use App\Services\BaoJianService;
use Dcat\Admin\Actions\Response;
use Dcat\Admin\Grid\RowAction;
use Dcat\Admin\Traits\HasPermissions;
use Illuminate\Contracts\Auth\Authenticatable;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cache;

class MachineOpen extends RowAction
{
    /**
     * @return string
     */
    protected $title = '开门';

    /**
     * Handle the action request.
     *
     * @param Request $request
     *
     * @return Response
     */
    public function handle(Request $request)
    {
        $device_code = $request->get('device_code');
        $machine_no = $request->get('machine_no');

        $res = Cache::has('open_machine_' . $machine_no . '_1');

        if($res) {
            return $this->response()
                ->error('设备已被占用')
                ->refresh();
        } else {
            $res = BaoJianService::openDoor($device_code, 1, 4);
        }

        if(!$res) {
            return $this->response()
                ->error('操作失败')
                ->refresh();
        }

        return $this->response()
            ->success('操作成功')
            ->refresh();
    }

    /**
     * @return string|array|void
     */
    public function confirm()
    {
        return ['确认操作吗?', '打开柜门'];
    }

    /**
     * @param Model|Authenticatable|HasPermissions|null $user
     *
     * @return bool
     */
    protected function authorize($user): bool
    {
        return true;
    }

    /**
     * @return array
     */
    protected function parameters()
    {
        return [
            'device_code'   => $this->row->device_code,
            'machine_no'    => $this->row->machine_no,
        ];
    }

    protected function html()
    {
        return <<<HTML
            <a {$this->formatHtmlAttributes()}><i class="feather icon-unlock text-success"></i> <span class="text-success">{$this->title}</span> &emsp;</a>
        HTML;
    }
}
